package cn.wangqi.personal.upload;

import cn.wangqi.personal.util.PropertiesUtil;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Calendar;
import java.util.Iterator;
import java.util.UUID;

/**
 * Created by admin on 2017/9/14.
 */
public class MultipartResolverFileUtil {

    Logger logger = Logger.getLogger(MultipartResolverFileUtil.class);

    public static String uploadFile(HttpServletRequest request) {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if (!multipartResolver.isMultipart(request)) {
            return "{\"state\":\"FAILER\"}";
        }
        //将request变成多部分request
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        //拼接:当前月/日/文件名+序号(随机序列)
        Calendar now = Calendar.getInstance();
        String yearMonth = now.get(Calendar.YEAR) + "/" + (now.get(Calendar.MONTH) + 1);
        int day = now.get(Calendar.DAY_OF_MONTH);
        //获取multiRequest 中所有的文件名
        Iterator iter = multiRequest.getFileNames();

        while (iter.hasNext()) {
            //一次遍历所有文件
            MultipartFile file = multiRequest.getFile(iter.next().toString());
            if (file != null) {
                String fileName = file.getOriginalFilename();
                if (fileName.trim() != "") {
                    //获取tomcat中的web-inf路径
                    //                        String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF");
                    String uploadPath = PropertiesUtil.getString("img_path");
                    StringBuffer stringBuffer = new StringBuffer();
                    //拼接格式为：资源路径/年月/日/用户/自定义文件夹名/图片原名，例如：F:/upload/201604/28/nijiwen/12/img10.jpg
                    stringBuffer.append("/img/").append(yearMonth).append("/").append(day).append("/");
                    //拼接访问的nginx路径
                    String accessDirectory = stringBuffer.toString();
                    String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
                    String remoteRandomFile = reNameFile(fileName)+fileSuffix;
                    //获取文件后缀
                    String accessURL = accessDirectory + remoteRandomFile;

                    //拼接上传的路径，tomcat服务器的某个地址，并上传文件
                    StringBuffer stringBuffer1 = new StringBuffer();
                    stringBuffer1.append(request.getSession().getServletContext().getRealPath(uploadPath)).append(yearMonth).append("/").append(day).append("/");
                    String realUploadDirectory = stringBuffer1.toString();
                    File uploadFileDirectory = new File(realUploadDirectory);
                    if (!uploadFileDirectory.exists()) {
                        uploadFileDirectory.mkdirs();
                    }
                    String path = realUploadDirectory + remoteRandomFile;
                    File localFile = new File(path);
                    try {
                        file.transferTo(localFile);
                        return "{\"state\": \"SUCCESS\",\"original\": \"Penguins.jpg\",\"size\": \"202263\",\"title\": \"1463049118845085104.jpg\",\"type\": \".jpg\",\"url\": \"" + accessURL + "\"}";
                    } catch (Exception e) {
                        return "{\"state\":\"EXCEPTION\"}";
                    }
                }
            }
        }
        return "{\"state\":\"EXCEPTION\"}";
    }

    private static String reNameFile(String oldFileName){
        String uuidName = UUID.randomUUID().toString() + "_"+oldFileName;
        int hash = uuidName.hashCode();
        String hashStr = Integer.toHexString(hash);
        return hashStr;
    }
}
